/**
 * @author LiuWeiNing
 * @version 0.1
 * 
 */

package model.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import dom.domain.User;
import dom.domain.UserDAO;

public class loginService {
	private UserDAO userDao;
	private Map<String, String> map;

	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}

	public String login(String userInfo,HttpSession session) {
		map = new HashMap<String, String>();
		session.setAttribute("isLogin", "false");
		try {
			JSONObject user = JSONObject.fromObject(userInfo);
			if (user == null) {
				map.put("flag", "flase");
				map.put("info", "data is empty");
				return JSONObject.fromObject(map).toString();
			}
			if (!user.containsKey("userId")) {
				map.put("flag", "flase");
				map.put("info", "userId is empty");
				return JSONObject.fromObject(map).toString();
			}
			User tempUser = userDao.findById(user.getString("userId"));
			if(tempUser==null)
			{

				map.put("flag", "flase");
				map.put("info", "用户名不存在");
				return JSONObject.fromObject(map).toString();
			}
			if (user.containsKey("psd")) {
				if (user.getString("psd").equals(tempUser.getPsd())) {
					map.put("flag", "true");
					map.put("info", "login sucessfully!");
					map.put("epState", Integer.toString(tempUser.getEpAllocated()));
					map.put("state", tempUser.getState());
					session.setAttribute("isLogin", "true");
				} else {
					map.put("flag", "false");
					map.put("info", "password is wrong");
				}
			} else {
				map.put("flag", "false");
				map.put("info", "password is empty");
			}
		} catch (JSONException e) {
			map.put("flag", "false");
			map.put("info", "data format error");
		}
		return JSONObject.fromObject(map).toString();
		// if()
	}

}
